#!/usr/bin/python
# vim: fdm=marker fmr={{{,}}} cms=#%s

import os
import sys
import socket
import re

SOAR=os.environ.get('SOAR')
if not SOAR:
    SOAR='/opt/soar'
sys.path.append(SOAR+'/common/python')
try:
    from soar import *
except ImportError:
    print >>sys.stderr, """\
Import soar fail 
%s
%s
""" % (sys.exc_value, sys.version)
    sys.exit(1)

class cnfg_info:
    server_port=0

def usage(selfname):
#{{{
    print "Usage: %s SERVICE [ para... ]" % selfname
#}}}

def cnfg():
#{{{
    import ConfigParser

    cnfg=os.environ.get('SVCENV_CNFG')
    if not cnfg:
        print "Error: SVCENV_CNFG not set"
        return 1

    try:
        file=open(cnfg, 'r');
    except:
        print "Error: open %s fail" % cnfg
        return 1 

    try:
        parser=ConfigParser.ConfigParser()
        parser.readfp(file)
        cnfg_info.server_port=int(parser.get('AGENT', 'SERVER_PORT'))
    except:
        print "Error: parse %s fail" % cnfg
        return 1

    return 0
#}}}

def call(sock, request):
#{{{
    request=misc.wrap_size(request)
    sock.sendall(request)
    buf=sock.recv(misc.MSG_SIZE_SIZE)
    if not buf: raise socket.error
    left_size=int(buf, base=16)
    respond=''
    while left_size > 0:
        buf=sock.recv(left_size)
        if not buf: raise socket.error
        respond+=buf
        left_size-=len(buf)
    return respond
#}}}

def main(argc, argv):
#{{{
    if argc < 2:
        usage(os.path.basename(argv[0]))
        return 1

    res=cnfg()
    if res: return 1

    sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.connect(('localhost', cnfg_info.server_port))
    except socket.gaierror, e:
        print "address-related error: %s" % e
        return 1
    except socket.error, e:
        print "connect to server fail: %s" % e
        return 1

    try:
        request=''
        request,size=para.put_item(request,"CALL")
        for item in argv[1:]:
            request,size=para.put_item(request,item)
        respond=call(sock, request)

        curr=0
        while 1:
            item,curr=para.get_item(respond,curr)
            if not item: break
            print item

        request=''
        request,size=para.put_item(request,"RELEASE")
        respond=call(sock, request)
        curr=0
        item,curr=para.get_item(respond,curr)
        print "RELEASE: %s" % item
    except socket.error:
        print "Error: sock operation fail"
        sock.close()
        return 1

    sock.close()
    return 0
#}}}

if __name__ == '__main__':
    main(len(sys.argv), sys.argv)
